#coding=utf-8

import os.path
import time
from datetime import date, datetime
from decimal import Decimal
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from jsonpickle import handlers
from tornado.options import define, options
from tornado_json.routes import get_routes
from tornado_json.application import Application
import models
import api
from project.tools import Session, Base
from project.handlers import HomeHandler, LogoutHandler

define("port", default=8888, help="run on the given port", type=int)

class MyDateHandler(handlers.BaseHandler):
    """
    注册日期特别处理
    """
    def flatten(self, obj, data):
        return int(time.mktime(obj.timetuple())*1000)

    def restore(self, data):
        t = time.localtime(data/1000)
        return date(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, t.tm_wday, t.tm_yday, t.tm_isdst)


class MyDecimalHandler(handlers.BaseHandler):
    def flatten(self, obj, data):
        return float(obj)

    def restore(self, data):
        return Decimal.from_float(data)



handlers.register(date, MyDateHandler)
handlers.register(datetime, MyDateHandler)
handlers.register(datetime, MyDateHandler)
handlers.register(Decimal, MyDecimalHandler)

class MyApplication(Application):
    def __init__(self):
        routes = get_routes(api)
        routes.extend([
            (r"/.*", HomeHandler),
            (r"/logout", LogoutHandler)
        ])
        print(routes)
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "../public"),
            cookie_secret='liubin',
            login_url='/login',
            #xsrf_cookies=True
            #debug=True
        )
        Application.__init__(self, routes, settings, Session)


def main():
    tornado.options.parse_command_line()
    #tornado.options.print_help()
    http_server = tornado.httpserver.HTTPServer(MyApplication())
    print('server start at ' + str(options.port) )
    print('please press ctrl + break to stop server')
    http_server.listen(options.port)
    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()


if __name__ == '__main__':
    main()